package com.lujianfei.powersearch.ui.subitem

import android.util.Log
import androidx.databinding.ViewDataBinding
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import java.util.*

class ActivityStackManager private constructor() {
    companion object {
        @JvmStatic
        var instance = ActivityStackManager()
    }

    private val stack = Stack<StackInfo>()
    fun push(stackInfo: StackInfo) {
        stack.push(stackInfo)
        Log.d("ActivityStackManager", "push " + stack + " size:" + stack.size)
    }

    fun remove(stackInfo: StackInfo): Boolean {
        val result = stack.remove(stackInfo)
        Log.d("ActivityStackManager", "removed " + stack + " size:" + stack.size)
        return result
    }

    fun peek(): StackInfo {
        return stack.peek()
    }

    fun popAndFinishToId(id: Long): Boolean {
        if (!containsParent(id)) {
            return false
        }
        while (!stack.isEmpty() && stack.peek().searchItemModel?.id != id) {
            Log.d("ActivityStackManager", "popAndFinishToId id = $id")
            val pop = stack.pop()
            pop.baseActivity.finish()
        }
        return true
    }

    private fun containsParent(id: Long): Boolean {
        for (stackInfo in stack) {
            if (stackInfo.searchItemModel?.id == id) {
                return true
            }
        }
        return false
    }

    class StackInfo(var searchItemModel: SearchItemModel?, var baseActivity: BaseActivity<ViewDataBinding>) {
        override fun toString(): String {
            return String.format("id=%s,title=%s", searchItemModel?.id, searchItemModel?.name)
        }
    }
}